from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection

from . import constants
from meiduo_mall.libs.captcha.captcha import captcha

import random
# from meiduo_mall.libs.yuntongxun.sms import CCP

from . import serializers

from celery_tasks.sms.tasks import send_sms_code
# import logging
# # 日志记录器
# logger = logging.getLogger('django')


class ImageCodeView(APIView):

    def get(self,request,image_code_id):

        text,image = captcha.generate_captcha()
        # logger.info(text)


        redis_conn=get_redis_connection('verify_codes')
        redis_conn.set('img_%s'%image_code_id,text,constants.IMAGE_CODE_REDIS_EXPIRES)
        print(text)
        return HttpResponse(image,content_type='image/jpg')


#获取短信验证码
class SMSCodeView(GenericAPIView):

    serializer_class = serializers.ImageCodeCheckSerializer
    def get(self,request,mobile):
        # 接受参数：mobile,image_code_id,text
        # 校验参数：比较用户传入的图片验证码和服务器存储的是否一致
        serializer= self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)


        #生成随机的短信验证码，发送短信的验证码，存储短信验证码，响应结果
        sms_code = "%06d"%random.randint(0,999999)

        # logger.info(sms_code)
        # CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES//60],1)

        #调用selery异步服务器发送短信验证码
        # send_sms_code.delay(mobile, sms_code)

        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.set('sms_%s'%mobile,sms_code,constants.SMS_CODE_REDIS_EXPIRES)
        print(sms_code)

        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVA, 1)
        pl.execute()
        return Response({'message':'OK'})


